@echo off

REM 打包部署脚本 - Windows版本
REM 使用方法: 双击运行或在命令提示符中执行

setlocal enabledelayedexpansion

REM 配置变量
set PROJECT_NAME=chatapp
set DEPLOY_DIR=%TEMP%\%PROJECT_NAME%_deployment
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "DATETIME=%%a"
set "DATETIME=%DATETIME:~0,4%%DATETIME:~4,2%%DATETIME:~6,2%_%DATETIME:~8,2%%DATETIME:~10,2%%DATETIME:~12,2%"
set OUTPUT_FILE=%PROJECT_NAME%_deployment_%DATETIME%.zip

REM 获取当前目录
set "BACKEND_DIR=%~dp0"
set "BACKEND_DIR=%BACKEND_DIR:~0,-1%"
for %%i in ("%BACKEND_DIR%") do set "ROOT_DIR=%%~dpi"
set "ROOT_DIR=%ROOT_DIR:~0,-1%"
set "FRONTEND_DIR=%ROOT_DIR%\frontend"

REM 确保脚本在backend目录下执行
if not "%BACKEND_DIR:~-7%"=="\backend" (
    echo ❌ 请在项目的backend目录下执行此脚本
    pause
    exit /b 1
)

cls
echo 🚀 开始打包%PROJECT_NAME%应用...
echo ==================================

REM 清理旧的打包目录
if exist "%DEPLOY_DIR%" (
    echo 🧹 清理旧的打包目录: %DEPLOY_DIR%
    rd /s /q "%DEPLOY_DIR%"
)

REM 创建新的打包目录
echo 📁 创建打包目录: %DEPLOY_DIR%
mkdir "%DEPLOY_DIR%"
mkdir "%DEPLOY_DIR%\backend"
mkdir "%DEPLOY_DIR%\instance"

REM 复制必要的文件和目录
echo 📋 复制项目文件...

REM 复制backend目录下的文件，但排除不需要的内容
echo    - 复制backend文件
xcopy "%BACKEND_DIR%" "%DEPLOY_DIR%\backend\" /E /I /Y ^
    /EXCLUDE:exclude_files.txt

REM 创建排除文件列表
if not exist "exclude_files.txt" (
    echo __pycache__\> exclude_files.txt
    echo *.pyc>> exclude_files.txt
    echo *.pyo>> exclude_files.txt
    echo *.pyd>> exclude_files.txt
    echo .env>> exclude_files.txt
    echo *.log>> exclude_files.txt
    echo uploads\*>> exclude_files.txt
    echo venv\>> exclude_files.txt
    echo myenv\>> exclude_files.txt
    echo .vscode\>> exclude_files.txt
    echo .idea\>> exclude_files.txt
    echo *.pid>> exclude_files.txt
    echo *.seed>> exclude_files.txt
    echo *.pid.lock>> exclude_files.txt
    echo .git\>> exclude_files.txt
    echo .gitignore>> exclude_files.txt
    echo pack_deployment.sh>> exclude_files.txt
    echo pack_deployment.bat>> exclude_files.txt
    echo exclude_files.txt>> exclude_files.txt
)

REM 复制前端文件（如果存在）
if exist "%FRONTEND_DIR%" (
    echo    - 复制frontend文件
    mkdir "%DEPLOY_DIR%\frontend"
    xcopy "%FRONTEND_DIR%" "%DEPLOY_DIR%\frontend\" /E /I /Y ^
        /EXCLUDE:exclude_frontend.txt
    
    REM 创建前端排除文件列表
    if not exist "exclude_frontend.txt" (
        echo __pycache__\> exclude_frontend.txt
        echo node_modules\>> exclude_frontend.txt
        echo dist\>> exclude_frontend.txt
        echo build\>> exclude_frontend.txt
        echo .git\>> exclude_frontend.txt
        echo .gitignore>> exclude_frontend.txt
    )
) else (
    echo    - 前端目录不存在，跳过
)

REM 复制根目录下的重要文件
echo    - 复制根目录文件
if exist "%ROOT_DIR%\docker-compose.yml" (
    copy "%ROOT_DIR%\docker-compose.yml" "%DEPLOY_DIR%\" >nul
) else (
    echo    - docker-compose.yml不存在，跳过
)

if exist "%ROOT_DIR%\README.md" (
    copy "%ROOT_DIR%\README.md" "%DEPLOY_DIR%\" >nul
) else (
    echo    - README.md不存在，跳过
)

REM 创建.env.example文件（如果不存在）
if not exist "%DEPLOY_DIR%\backend\.env.example" (
    echo 📝 创建.env.example文件
    (echo # 应用配置
echo APP_ENV=production
echo APP_DEBUG=False
echo APP_SECRET_KEY=your-secret-key
echo PORT=5000

echo # 数据库配置
echo DATABASE_URL=postgresql://username:password@localhost:5432/chatapp
echo # 或使用SQLite（开发环境）
echo # DATABASE_URL=sqlite:///../instance/test.db

echo # JWT配置
echo JWT_SECRET_KEY=your-jwt-secret-key
echo JWT_ACCESS_TOKEN_EXPIRES=86400  # 24小时

echo # Redis配置
echo REDIS_URL=redis://localhost:6379/0

echo # CORS配置
echo CORS_ALLOWED_ORIGINS=https://your-domain.com

echo # SSL配置（可选）
echo # SSL_CERT=path/to/cert.pem
echo # SSL_KEY=path/to/key.pem
echo # SSL_CONTEXT=adhoc
) > "%DEPLOY_DIR%\backend\.env.example"
)

REM 创建部署指南
echo 📖 创建部署指南
(
echo # %PROJECT_NAME%部署指南


echo ## 前提条件


echo 在新服务器上需要安装以下软件:
echo - Docker
echo - Docker Compose
echo - Git (可选)
echo - curl
echo - bash


echo ## 部署步骤


echo 1. **复制部署包到目标服务器**
echo    ```bash
echo    scp %OUTPUT_FILE% user@your-server:/path/to/destination
echo    ```


echo 2. **登录到目标服务器**
echo    ```bash
echo    ssh user@your-server
echo    ```


echo 3. **解压部署包**
echo    ```bash
echo    unzip %OUTPUT_FILE%
echo    cd %PROJECT_NAME%_deployment
echo    ```


echo 4. **配置环境变量**
echo    ```bash
echo    cd backend
echo    cp .env.example .env
echo    nano .env  # 编辑环境变量配置
echo    cd ..
echo    ```


echo 5. **启动Docker容器**
echo    ```bash
echo    docker compose up -d --build
echo    ```


echo 6. **检查服务状态**
echo    ```bash
echo    docker compose ps
echo    docker compose logs -f
echo    ```


echo 7. **更新域名配置** (如果使用Cloudflare隧道)
echo    ```bash
echo    cd backend
echo    chmod +x renew_domain.sh restore_domain_cache.sh
echo    ./renew_domain.sh
echo    ```


echo ## 常见问题排查


echo - **服务无法启动**: 检查.env配置和Docker日志
echo - **数据库连接错误**: 确保数据库配置正确且数据库服务正常
echo - **WebSocket连接问题**: 检查nginx配置和CORS设置
echo - **域名访问问题**: 运行renew_domain.sh脚本更新域名配置


echo ## 维护命令


echo - 停止服务: `docker compose down`
echo - 重启服务: `docker compose restart`
echo - 查看日志: `docker compose logs [service_name]`
echo - 更新代码后重建: `docker compose up -d --build`
) > "%DEPLOY_DIR%\DEPLOYMENT_GUIDE.md"

REM 创建启动部署的辅助脚本
echo 🔧 创建辅助部署脚本
(
echo #!/bin/bash


echo # 一键部署脚本


echo set -euo pipefail


echo # 配置环境变量
echo echo "🔧 配置环境变量..."
echo if [ ! -f "backend/.env" ]; then
echo     cp backend/.env.example backend/.env
echo     echo "⚠️  .env文件已创建，请先编辑配置，然后重新运行此脚本"
echo     echo "📝 编辑命令: nano backend/.env"
echo     exit 1
echo fi


echo # 启动Docker容器
echo echo "🚀 启动Docker容器..."
echo docker compose up -d --build


echo # 等待服务启动
echo echo "⏳ 等待服务启动..."
echo sleep 10


echo # 检查容器状态
echo echo "✅ 容器状态:"
echo docker compose ps


echo # 运行域名更新脚本
echo echo "🌐 更新域名配置..."
echo cd backend
echo chmod +x renew_domain.sh restore_domain_cache.sh
echo ./renew_domain.sh
echo cd ..


echo # 显示部署完成信息
echo echo "🎉 部署完成！"
echo echo "📌 请访问脚本输出的域名查看应用"
echo echo "🔧 如需查看日志: docker compose logs -f"
) > "%DEPLOY_DIR%\deploy.sh"

REM 压缩打包目录
echo 📦 压缩部署包...
cd "%DEPLOY_DIR%"
powershell -command "Compress-Archive -Path * -DestinationPath '%TEMP%\%OUTPUT_FILE%' -Force"
cd "%BACKEND_DIR%"

REM 移动压缩包到当前目录
move "%TEMP%\%OUTPUT_FILE%" "%BACKEND_DIR%\%OUTPUT_FILE%" >nul

REM 清理临时文件
echo 🧹 清理临时文件...
rd /s /q "%DEPLOY_DIR%"
del exclude_files.txt 2>nul
del exclude_frontend.txt 2>nul

REM 显示完成信息
echo ✅ 打包完成！
echo ==================================
echo 输出文件: %BACKEND_DIR%\%OUTPUT_FILE%
echo 部署指南: 请查看压缩包内的DEPLOYMENT_GUIDE.md
echo 快速部署: 解压后运行deploy.sh脚本
echo ==================================

pause